package com.yeskery.nut.http.nio;

import com.yeskery.nut.application.NutApplication;
import com.yeskery.nut.http.BaseResponse;
import com.yeskery.nut.util.IOUtils;

import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

/**
 * 基于 <b>NIO</b> 模式下的 {@link com.yeskery.nut.core.Response} 的实现，该类继承自 {@link BaseResponse}
 * @author sprout
 * @version 1.0
 * 2019-03-19 00:50
 */
public class NioResponse extends BaseResponse {

	/** 用于承载数据的字节集合 */
    private final List<Byte> byteList = new LinkedList<>();

	/**
	 * 构建一个NIO响应对象
	 * @param nutApplication Nut应用对象
	 */
	public NioResponse(NutApplication nutApplication) {
		super(nutApplication);
	}

	@Override
	protected void writeHeaderBytes(byte[] headers) {
		for (byte b : headers) {
			byteList.add(b);
		}
	}

	@Override
	protected void writeBodyBytes(byte[] bytes) {
		for (byte b : bytes) {
			byteList.add(b);
		}
	}

	@Override
	protected void writeBodyInputStream(InputStream inputStream) {
		for (byte b : IOUtils.readByteArray(inputStream)) {
			byteList.add(b);
		}
	}

	@Override
    protected void writeBytes(byte[] headers, byte[] bytes) {
    	for (byte b : headers) {
			byteList.add(b);
		}
    	for (byte b : bytes) {
			byteList.add(b);
		}
		output = true;
    }

	@Override
	protected void writeInputStream(byte[] headers, InputStream inputStream) {
		for (byte b : headers) {
			byteList.add(b);
		}
		for (byte b : IOUtils.readByteArray(inputStream)) {
			byteList.add(b);
		}
		output = true;
	}

	/**
	 * 获取当前响应中的所有字节数组
	 * @return 当前响应中的所有字节数组
	 */
	public byte[] getBytes() {
    	int i = 0;
    	byte[] bytes = new byte[byteList.size()];
    	for (Byte b : byteList) {
			bytes[i++] = b;
		}
    	return bytes;
	}
}
